﻿namespace PropOnline.Stores.Data
{
    using System;
    using System.Data.Objects;
    using System.Linq.Expressions;

    public static class ObjectQueryExtensions
    {
        public static ObjectQuery<T> Include<T>(this ObjectQuery<T> source, Expression<Func<T, object>> exp)
        { 
            var path = GetPath(exp); 
            return source.Include(path);
        }

        // TODO: Se se usa, borrar?
        public static T ValueOrDefault<T>(T obj, T defaultValue)
        {
            return obj != null ? obj : defaultValue;
        }

        // TODO: Se se usa, borrar?
        public static RT TransformValueOrDefault<T, RT>(T obj, Func<T, RT> transformation, RT defaultValue)
        {
            return obj != null ? transformation(obj) : defaultValue;
        }

        private static string GetPath(Expression exp) 
        {
            switch (exp.NodeType)
            {
                case ExpressionType.MemberAccess:
                    var name = GetPath(((MemberExpression)exp).Expression) ?? string.Empty;
                    if (name.Length > 0)
                    {
                        name += ".";
                    }

                    return name + ((MemberExpression)exp).Member.Name;
                case ExpressionType.Convert:
                case ExpressionType.Quote: 
                    return GetPath(((UnaryExpression)exp).Operand);
                case ExpressionType.Lambda: 
                    return GetPath(((LambdaExpression)exp).Body);
                default:
                    return null;
            }
        }
    }
}